<?php
namespace Modules\User\Controllers;

class IndexController extends \Phalcon\Mvc\Controller {
	public function initialize() {
		$this -> response -> setStatusCode(200, 'OK') -> sendHeaders() -> setContentType('application/json', 'UTF-8');
	}

	public function indexAction() {
		//return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'user' => $service['user']]);
		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'user' => 'user']);
	}

	public function findFirstByIdAction($id) {
		$service = $this -> user::getServiceInstance() -> findFirstById($id);
		if($service['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'账号不存在!']);
		}
		$service['user'] = $service['user'] -> toArray();
		unset($service['user']['password']);
		unset($service['user']['safe_password']);

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'user' => $service['user']]);
	}

	public function findFirstByAccountAction($account) {
		$service = $this -> user::getServiceInstance() -> findFirstByAccount($account);
		if($service['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'账号不存在!']);
		}
		$service['user'] = $service['user'] -> toArray();
		unset($service['user']['password']);
		unset($service['user']['safe_password']);

		$resUserInfo = $this -> user::getInfoServiceInstance() -> findFirstById($service['user']['user_id']);
		if($resUserInfo['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'user' => $service['user'],'user_info'=>['real_name'=>'对方未认证']]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'user' => $service['user'],'user_info'=>$resUserInfo['user_info']]);
	}

	public function createAction() {
		$validation = $this -> user::getValidationInstance()
		-> addPAccount()
		-> addCellphoneUniqueness()
		-> addAccountUniqueness()
		-> addPassword()
		-> addSafePassword()
		-> addLevel()
		-> addStatus()
		-> execute($this -> request -> getPost());
		if($validation['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$validation['code'],'msg'=>$validation['message']]);
		}
		
		if(isset($validation['data']['captchaToken'])) {
			if(base64_decode($validation['data']['captchaToken']) != md5($validation['data']['captcha'])) {
				return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'验证码错误']);
			}
		}

		/*
		$res = $this -> user::getServiceInstance() -> find([
			'columns' => 'user_id, pid',
			'order' => 'user_id ASC'
		]);
		foreach($res['user'] as $user) {
			$this -> updateLevel($user -> pid, $user);
		}
		exit;
		*/
		$filter = $this -> user::getFilterInstance()
		-> setData($validation['data'])
		-> addPAccount()
		-> addCellphone()
		-> addAccount()
		-> addPassword($this -> getDI())
		-> addSafePassword($this -> getDI())
		-> addLevel()
		-> addStatus()
		-> setCreateTime()
		-> setLastUpdateTime()
		-> execute();
		if($filter['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$filter['code'],'msg'=>$filter['message']]);
		}

		$service = $this -> user::getServiceInstance() -> create($filter['data']);
		if($service['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$service['code'],'msg'=>$service['message']]);
		}

		try {
			$this -> updateLevel($filter['data']['pid'], $service['user']);
		} catch(\Exception $e) {
		  file_put_contents(PUBLIC_PACH.'IndexController.updateLevel.error.txt', 'Line: ' . $e -> getLine() . ', Message: ' . $e -> getMessage() . '.' . PHP_EOL, \FILE_APPEND);
		}
		
		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'创建成功']);
	}

	public function updateLevel($pid, $user) {
		if($pid != 0) {
			$findFirstCurrentParent = $this -> getUsers($pid);

			$parentUserIds = '';
			while(true) {
				if($findFirstCurrentParent['code'] != 0) { break; }

				$parentUserIds .= $findFirstCurrentParent['user'] -> user_id . ',';

				if($findFirstCurrentParent['user'] -> pid == 0) { break; }

				$findFirstCurrentParent = $this -> getUsers($findFirstCurrentParent['user'] -> pid);
			}
			unset($findFirstCurrentParent);

			$parentUserIds = rtrim($parentUserIds, ',');

			$resFindUserTeam = $this -> user::getTeamServiceInstance() -> find([
				'conditions' => 'user_id in (' . $parentUserIds . ')',
				'order' => 'user_id ASC'
			]);
			$parentUserIdArray = explode(',', $parentUserIds);
			unset($parentUserIds);
			if($resFindUserTeam['code'] != 0) {
				$userTeams = [];
			} else {
				$userTeams = [];
				foreach($resFindUserTeam['models'] as $userTeam) {
					$userTeams[$userTeam -> user_id] = $userTeam;
				}
				unset($userTeam);
			}
			unset($resFindUserTeam);

			$currentTime = time();
			foreach($parentUserIdArray as $userId) {
				if(!isset($userTeams[$userId]) || empty($userTeams[$userId])) {
					$userTeams[$userId] = $this -> user::getTeamServiceInstance() -> getNewModel([
						'user_id' => $userId,
						'data' => '{}',
						'create_time' => $currentTime
					]);
				}
			}
			unset($parentUserIdArray);
			unset($userId);

			$layerNum = 1;
			rsort($userTeams);
			foreach($userTeams as $userTeam) {
				$userTeamData = json_decode($userTeam -> data, true);
				if(!isset($userTeamData[$layerNum])) {
					$userTeamData[$layerNum] = [];
				}

				$userTeamData[$layerNum][$user -> user_id] = [];
				$countUserTeamData = 0;
				if(isset($userTeamData[1])) {
					$countUserTeamData = count($userTeamData[1]);
				}

				$currentUser = $this -> getUsers($userTeam -> user_id);
				if($currentUser['code'] != 0) {
					continue;
				}
				if($countUserTeamData >= 10) {
					if($currentUser['user'] -> level != 4) {
						$findParentUserChildren = $this -> user::getServiceInstance() -> find([
							'conditions' => 'level in(3, 4) AND pid = ' . $userTeam -> user_id,
							'columns' => 'level'
						]);
						if($findParentUserChildren['code'] != 0) {
							
						} else {
							if($findParentUserChildren['user'] -> count() >= 2) {
								$currentUser['user'] -> level = 4;
								$currentUser['user'] -> save();
							}
						}
						unset($findParentUserChildren);
					}
				} else if($countUserTeamData >= 5) {
					if($currentUser['user'] -> level != 3) {
						$currentUser['user'] -> level = 3;
						$currentUser['user'] -> save();
					}
				} else if($countUserTeamData >= 2) {
					if($currentUser['user'] -> level != 2) {
						$currentUser['user'] -> level = 2;
						$currentUser['user'] -> save();
					}
				}

				$userTeam -> data = json_encode($userTeamData);
				$userTeam -> save();
				$layerNum++;
				unset($currentUser);
				unset($userTeamData);
			}
			unset($userTeam);
			unset($layerNum);
			unset($userTeams);
		}
	}

	private $users = [];
	public function getUsers($user_id = null) {
		if(is_null($user_id)) {
			return $this -> users;
		}

		if(isset($this -> users[$user_id])) {
			return $this -> users[$user_id];
		}

		return $this -> users[$user_id] = $this -> user::getServiceInstance() -> findFirst('user_id = ' . $user_id);
	}
	
	public function updateAction($id) {
		$validation = $this -> user::getValidationInstance()
		-> addPAccount()
		-> addLevel()
		-> addStatus()
		-> addCellphone()
		-> execute($this -> request -> getPut());
		if($validation['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$validation['code'],'msg'=>$validation['message']]);
		}

		$filter = $this -> user::getFilterInstance()
		-> setData($validation['data'])
		-> addPAccount()
		-> addAccount()
		-> addPassword($this -> getDI())
		-> addSafePassword($this -> getDI())
		-> addLevel()
		-> addStatus()
		-> setLastUpdateTime()
		-> execute();
		if($filter['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$filter['code'],'msg'=>$filter['message']]);
		}

		$service = $this -> user::getServiceInstance() -> update($id, $filter['data']);
		if($service['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$service['code'],'msg'=>$service['message']]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'修改成功']);
	}

	public function deleteAction($id) {
		$service = $this -> products::getServiceInstance() -> delete($id);
		if($service['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$service['code'],'msg'=>$service['message']]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'删除成功']);
	}
}